<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="旅行社" prop="travel_agency_id">
                    <el-select
                        class="flex-1"
                        v-model="formData.travel_agency_id"
                        clearable
                        placeholder="请选择旅行社"
                    >
                        <el-option
                            v-for="(item, index) in optionsData.trave_agency"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <!-- 标签选择 -->
                <el-form-item label="标签" prop="tags">
                    <el-checkbox-group v-model="formData.tags">
                        <el-checkbox
                            v-for="item in tags_data"
                            :key="item.id"
                            :value="item.name"
                            :label="item.name"
                        />
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="线路名称" prop="title">
                    <el-input v-model="formData.title" clearable placeholder="请输入线路名称" />
                </el-form-item>
                <el-form-item label="出发地点" prop="start_address">
                    <el-input
                        v-model="formData.start_address"
                        clearable
                        placeholder="请输入出发地点"
                    />
                </el-form-item>
                <el-form-item label="到达地点" prop="end_address">
                    <el-input
                        v-model="formData.end_address"
                        clearable
                        placeholder="请输入到达地点"
                    />
                </el-form-item>
                <el-form-item label="线路图片" prop="line_image">
                    <material-picker v-model="formData.line_image" />
                </el-form-item>
                <el-form-item label="简介" prop="desc">
                    <el-input
                        class="flex-1"
                        v-model="formData.desc"
                        type="textarea"
                        clearable
                        placeholder="请输入简介"
                    />
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <editor class="flex-1" v-model="formData.content" :height="500" />
                </el-form-item>
                <el-form-item label="是否热门" prop="is_hot">
                    <el-radio-group v-model="formData.is_hot" placeholder="请选择是否热门线路">
                        <el-radio
                            v-for="(item, index) in dictData.is_hot"
                            :key="index"
                            :value="parseInt(item.value)"
                        >
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <div>
                        <el-input-number v-model="formData.sort" :min="0" :max="9999" />
                        <div class="form-tips">默认为0， 数值越大越排前</div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="lineEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLineAdd, apiLineEdit, apiLineDetail } from '@/api/line'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { travelAgencyAll } from '@/api/travel_agency.ts'
import { useDictOptions } from '@/hooks/useDictOptions.ts'
import { getSearch } from '@/api/setting/search.ts'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑线路表' : '新增线路表'
})

// 表单数据
const formData = reactive({
    id: '',
    travel_agency_id: '',
    title: '',
    start_address: '',
    end_address: '',
    line_image: '',
    desc: '',
    content: '',
    is_hot: 0,
    sort: 0,
    user_id: 0,
    tags: [] as string[]
})

// 表单验证
const formRules = reactive<any>({
    travel_agency_id: [
        {
            required: true,
            message: '请选择旅行社ID',
            trigger: ['blur']
        }
    ],
    title: [
        {
            required: true,
            message: '请输入线路名称',
            trigger: ['blur']
        }
    ],
    start_address: [
        {
            required: true,
            message: '请输入出发地点',
            trigger: ['blur']
        }
    ],
    end_address: [
        {
            required: true,
            message: '请输入到达地点',
            trigger: ['blur']
        }
    ],
    line_image: [
        {
            required: true,
            message: '请选择线路图片',
            trigger: ['blur']
        }
    ]
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            // 显式处理 tags 字段
            if (key === 'tags') {
                if (Array.isArray(data.tags)) {
                    formData.tags = [...data.tags] // 深拷贝数组
                } else if (typeof data.tags === 'string') {
                    formData.tags = data.tags
                        .split(',')
                        .map((tag) => tag.trim())
                        .filter(Boolean)
                } else {
                    formData.tags = []
                }
            } else {
                formData[key] = data[key]
            }
        }
    }
    // if (data.tags) {
    //     formData.tags = data.tags.map((tag: any) => tag.name) // 假设传入数据为对象数组
    // }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiLineDetail({
        id: row.id
    })
    // 强制类型转换逻辑
    if (typeof data.tags === 'string') {
        data.tags = data.tags
            .split(',')
            .map((tag) => tag.trim())
            .filter(Boolean) // ["推荐", "错峰出行"]
    }

    setFormData(data)
}
// 标签数据
const tags_data = ref<{ id: number; name: string }[]>([])

// 加载标签数据
const loadTags = async () => {
    try {
        const res = await getSearch()
        tags_data.value = res.data.map((item, index) => ({
            id: item.id || index + 1,
            name: item.name
        }))
    } catch (error) {
        console.error('获取标签失败:', error)
    }
}
// 在组件挂载时加载数据
onMounted(() => {
    loadTags()
})

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const submitData = { ...formData }

    // 数组 → 字符串转换
    if (Array.isArray(submitData.tags)) {
        submitData.tags = submitData.tags.join(',') // "推荐,错峰出行"
    }

    mode.value == 'edit' ? await apiLineEdit(submitData) : await apiLineAdd(submitData)
    popupRef.value?.close()
    emit('success')
}

const { optionsData } = useDictOptions<{
    trave_agency: any[]
}>({
    trave_agency: {
        api: travelAgencyAll
    }
})

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail,
    tags_data
})
</script>
